﻿using System;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
using UnityEngine.Events;

namespace Assets.XiaoXiao.Script
{
    class JoystickCircle : ScrollRect 
    {
        
        [System.Serializable]  
        public class VirtualJoystickEvent : UnityEvent<Vector3> { }
        protected float radius;
        public UnityEvent beginControl; 
        public VirtualJoystickEvent controlling; 
        public UnityEvent endControl;

        private Move m_iObj; 
        protected override void Start()
        {
            this.radius = (transform as RectTransform).sizeDelta.x * 0.5f;
             m_iObj   = GameObject.FindGameObjectWithTag("Move").GetComponent<Move>();
            beginControl.AddListener(m_iObj.BeginMove);
            controlling.AddListener(m_iObj.UpdateDirection);
            endControl.AddListener(m_iObj.EndMove);
            
        }
        public override void OnBeginDrag(PointerEventData eventData)
        {
            this.beginControl.Invoke();
        }

        public override void OnDrag(PointerEventData eventData)
        {
            base.OnDrag(eventData);
            base.content.anchoredPosition = Vector3.ClampMagnitude(base.content.anchoredPosition, this.radius);
            if (this.content)
            {
               this.controlling.Invoke(this.content.localPosition.normalized);
            }
        }

        public override void OnEndDrag(PointerEventData eventData)
        {
            this.endControl.Invoke();
        }
    }
}
